package com.lmf.mock.starter.autoconfigure.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lmf.mock.starter.autoconfigure.entity.MockApi;
import com.lmf.mock.starter.autoconfigure.entity.MockGroup;
import com.lmf.mock.starter.autoconfigure.service.MockApiService;
import com.lmf.mock.starter.autoconfigure.service.MockGroupService;
import com.lmf.mock.starter.autoconfigure.service.RealDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * Mock数据管理控制器
 * 包含数据导出、导入和真实数据拉取功能
 */
@RestController
@RequestMapping("/mock/data")
public class MockDataController {

    @Autowired
    private MockApiService mockApiService;
    
    @Autowired
    private MockGroupService mockGroupService;
    
    @Autowired
    private RealDataService realDataService;

    /**
     * 从真实URL拉取数据
     */
    @PostMapping("/fetch-real")
    public ResponseEntity<Map<String, Object>> fetchRealData(@RequestBody Map<String, Object> request) {
        try {
            Long apiId = Long.valueOf(request.get("apiId").toString());
            
            String realData = realDataService.fetchRealData(apiId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", realData);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "拉取真实数据失败: " + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 按分组批量拉取真实数据
     */
    @PostMapping("/fetch-real-by-group")
    public ResponseEntity<Map<String, Object>> fetchRealDataByGroup(@RequestBody Map<String, Object> request) {
        try {
            Long groupId = Long.valueOf(request.get("groupId").toString());
            
            Map<String, Object> batchResult = realDataService.fetchRealDataByGroup(groupId);
            
            return ResponseEntity.ok(batchResult);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "批量拉取真实数据失败: " + e.getMessage());
            result.put("successCount", 0);
            result.put("failCount", 0);
            result.put("details", new HashMap<>());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 导出Mock数据
     */
    @GetMapping("/export")
    public ResponseEntity<String> exportData(@RequestParam(value = "groupId", required = false) Long groupId) {
        try {
            List<MockGroup> groups;
            List<MockApi> apis;
            
            if (groupId != null) {
                // 按分组导出
                MockGroup group = mockGroupService.getById(groupId);
                if (group == null) {
                    return ResponseEntity.status(404).body("{\"error\":\"分组不存在\"}");
                }
                groups = Collections.singletonList(group);
                apis = mockApiService.getApisByGroupId(groupId);
            } else {
                // 导出全部
                groups = mockGroupService.list();
                apis = mockApiService.list();
            }
            
            Map<String, Object> exportData = new HashMap<>();
            exportData.put("groups", groups);
            exportData.put("apis", apis);
            exportData.put("exportTime", System.currentTimeMillis());
            exportData.put("version", "1.0");
            exportData.put("exportType", groupId != null ? "group" : "all");
            if (groupId != null) {
                exportData.put("groupId", groupId);
            }
            
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonData = objectMapper.writeValueAsString(exportData);
            
            String filename = groupId != null ? 
                "mock-data-group-" + groupId + ".json" : "mock-data.json";
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(jsonData);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("{\"error\":\"导出失败: " + e.getMessage() + "\"}");
        }
    }

    /**
     * 导入Mock数据
     */
    @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Map<String, Object>> importData(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "importMode", defaultValue = "all") String importMode,
            @RequestParam(value = "selectedGroupIds", required = false) String selectedGroupIds,
            @RequestParam(value = "groupRenames", required = false) String groupRenames) {
        Map<String, Object> result = new HashMap<>();
        
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "文件不能为空");
            return ResponseEntity.ok(result);
        }
        
        try {
            String content = new String(file.getBytes(), "UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            @SuppressWarnings("unchecked")
            Map<String, Object> importData = objectMapper.readValue(content, Map.class);
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> groups = (List<Map<String, Object>>) importData.get("groups");
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> apis = (List<Map<String, Object>>) importData.get("apis");
            
            // 解析选中的分组ID
            List<Long> selectedIds = new ArrayList<>();
            if ("selected".equals(importMode) && selectedGroupIds != null && !selectedGroupIds.trim().isEmpty()) {
                try {
                    String[] idStrings = selectedGroupIds.split(",");
                    for (String idStr : idStrings) {
                        selectedIds.add(Long.valueOf(idStr.trim()));
                    }
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "选择的分组ID格式错误");
                    return ResponseEntity.ok(result);
                }
            }
            
            // 解析分组重命名信息
            Map<String, Map<String, String>> groupRenameMap = new HashMap<>();
            if (groupRenames != null && !groupRenames.trim().isEmpty()) {
                try {
                    ObjectMapper renameMapper = new ObjectMapper();
                    @SuppressWarnings("unchecked")
                    Map<String, Map<String, String>> renames = renameMapper.readValue(groupRenames, Map.class);
                    groupRenameMap = renames;
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "分组重命名信息格式错误");
                    return ResponseEntity.ok(result);
                }
            }
            
            int importedGroups = 0;
            int importedApis = 0;
            
            // 导入分组
            if (groups != null) {
                for (Map<String, Object> groupData : groups) {
                    // 如果是按选择导入，检查是否在选中列表中
                    if ("selected".equals(importMode)) {
                        Long originalGroupId = Long.valueOf(groupData.get("id").toString());
                        if (!selectedIds.contains(originalGroupId)) {
                            continue;
                        }
                    }
                    
                    MockGroup group = new MockGroup();
                    String originalGroupId = groupData.get("id").toString();
                    
                    // 检查是否有重命名信息
                    if (groupRenameMap.containsKey(originalGroupId)) {
                        Map<String, String> renameInfo = groupRenameMap.get(originalGroupId);
                        group.setGroupName(renameInfo.get("newName"));
                        group.setDescription(renameInfo.get("newDescription"));
                    } else {
                        group.setGroupName((String) groupData.get("groupName"));
                        group.setDescription((String) groupData.get("description"));
                    }
                    
                    group.setSortOrder((Integer) groupData.getOrDefault("sortOrder", 0));
                    group.setEnabled((Boolean) groupData.getOrDefault("enabled", true));
                    
                    if (mockGroupService.createGroup(group)) {
                        importedGroups++;
                    }
                }
            }
            
            // 导入接口
            if (apis != null) {
                for (Map<String, Object> apiData : apis) {
                    // 如果是按选择导入，检查接口所属分组是否在选中列表中
                    if ("selected".equals(importMode)) {
                        Long originalGroupId = Long.valueOf(apiData.get("groupId").toString());
                        if (!selectedIds.contains(originalGroupId)) {
                            continue;
                        }
                    }
                    
                    MockApi api = new MockApi();
                    api.setGroupId(Long.valueOf(apiData.get("groupId").toString()));
                    api.setApiName((String) apiData.get("apiName"));
                    api.setApiPath((String) apiData.get("apiPath"));
                    api.setHttpMethod((String) apiData.get("httpMethod"));
                    api.setRequestParams((String) apiData.get("requestParams"));
                    api.setParamMatchRules((String) apiData.get("paramMatchRules"));
                    api.setRealUrl((String) apiData.get("realUrl"));
                    api.setResponseData((String) apiData.get("responseData"));
                    api.setStatusCode((Integer) apiData.getOrDefault("statusCode", 200));
                    api.setDelayMs((Integer) apiData.getOrDefault("delayMs", 0));
                    api.setSortOrder((Integer) apiData.getOrDefault("sortOrder", 0));
                    api.setEnabled((Boolean) apiData.getOrDefault("enabled", true));
                    
                    if (mockApiService.createApi(api)) {
                        importedApis++;
                    }
                }
            }
            
            result.put("success", true);
            result.put("message", String.format("成功导入 %d 个分组，%d 个接口", importedGroups, importedApis));
            result.put("importedGroups", importedGroups);
            result.put("importedApis", importedApis);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "导入失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 预览导入数据，返回文件中的分组信息供用户选择
     */
    @PostMapping(value = "/import/preview", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Map<String, Object>> previewImportData(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "文件不能为空");
            return ResponseEntity.ok(result);
        }
        
        try {
            String content = new String(file.getBytes(), "UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            @SuppressWarnings("unchecked")
            Map<String, Object> importData = objectMapper.readValue(content, Map.class);
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> groups = (List<Map<String, Object>>) importData.get("groups");
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> apis = (List<Map<String, Object>>) importData.get("apis");
            
            // 统计每个分组下的接口数量
            Map<String, Integer> groupApiCount = new HashMap<>();
            if (apis != null) {
                for (Map<String, Object> api : apis) {
                    String groupId = api.get("groupId").toString();
                    groupApiCount.put(groupId, groupApiCount.getOrDefault(groupId, 0) + 1);
                }
            }
            
            // 构建预览数据
            List<Map<String, Object>> groupsPreview = new ArrayList<>();
            if (groups != null) {
                for (Map<String, Object> group : groups) {
                    Map<String, Object> preview = new HashMap<>();
                    preview.put("id", group.get("id"));
                    preview.put("groupName", group.get("groupName"));
                    preview.put("description", group.get("description"));
                    preview.put("apiCount", groupApiCount.getOrDefault(group.get("id").toString(), 0));
                    groupsPreview.add(preview);
                }
            }
            
            result.put("success", true);
            result.put("groups", groupsPreview);
            result.put("totalGroups", groups != null ? groups.size() : 0);
            result.put("totalApis", apis != null ? apis.size() : 0);
            result.put("exportTime", importData.get("exportTime"));
            result.put("version", importData.get("version"));
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "文件解析失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
}